// 全局变量
let stockTable;
let editingId = null;
let token = '';
let header = '';

// 页面加载完成后执行
$(document).ready(function() {
    // 获取CSRF令牌
    token = $("meta[name='_csrf']").attr("content");
    header = $("meta[name='_csrf_header']").attr("content");
    
    // 添加CSRF令牌到所有AJAX请求
    $.ajaxSetup({
        beforeSend: function(xhr) {
            xhr.setRequestHeader(header, token);
        }
    });

    // 初始化DataTable
    stockTable = $('#stockTable').DataTable({
        "processing": true,
        "serverSide": false,
        "ajax": {
            "url": "/stock/list",
            "type": "GET",
            "dataSrc": function(json) {
                if (json.code === 200 && json.data) {
                    return json.data;
                }
                return [];
            }
        },
        "columns": [
            {"data": "stockId"},
            {"data": "productName"},
            {"data": "productCode"},
            {"data": "warehouseName"},
            {"data": "quantity"},
            {"data": "unit"},
            {
                "data": null,
                "render": function(data) {
                    return '¥' + (data.quantity * data.price).toFixed(2);
                }
            },
            {"data": "lastInTime"},
            {"data": "lastOutTime"},
            {
                "data": null,
                "render": function(data) {
                    const quantity = data.quantity;
                    const warningQuantity = data.warningQuantity;
                    
                    if (quantity <= 0) {
                        return '<span class="badge badge-danger">缺货</span>';
                    } else if (quantity <= warningQuantity) {
                        return '<span class="badge badge-warning">库存低</span>';
                    } else {
                        return '<span class="badge badge-success">正常</span>';
                    }
                }
            },
            {
                "data": null,
                "render": function(data) {
                    return '<div class="btn-group" role="group">' +
                        '<button type="button" class="btn btn-sm btn-info action-btn" onclick="viewStock(' + data.stockId + ')">' +
                        '<i class="fas fa-eye"></i></button>' +
                        '<button type="button" class="btn btn-sm btn-primary action-btn" onclick="editStock(' + data.stockId + ')">' +
                        '<i class="fas fa-edit"></i></button>' +
                        '<button type="button" class="btn btn-sm btn-warning action-btn" onclick="showOutStockModal(' + data.stockId + ')">' +
                        '<i class="fas fa-sign-out-alt"></i></button>' +
                        '<button type="button" class="btn btn-sm btn-danger action-btn" onclick="showDeleteModal(' + data.stockId + ')">' +
                        '<i class="fas fa-trash-alt"></i></button>' +
                        '</div>';
                }
            }
        ],
        "language": {
            "emptyTable": "没有数据",
            "info": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
            "infoEmpty": "显示第 0 至 0 项结果，共 0 项",
            "infoFiltered": "(由 _MAX_ 项结果过滤)",
            "infoPostFix": "",
            "thousands": ",",
            "lengthMenu": "显示 _MENU_ 项结果",
            "loadingRecords": "载入中...",
            "processing": "处理中...",
            "search": "搜索:",
            "zeroRecords": "没有匹配结果",
            "paginate": {
                "first": "首页",
                "last": "末页",
                "next": "下页",
                "previous": "上页"
            },
            "aria": {
                "sortAscending": ": 以升序排列此列",
                "sortDescending": ": 以降序排列此列"
            }
        },
        "responsive": true,
        "lengthChange": true,
        "autoWidth": false,
        "searching": false,
        "paging": true,
        "info": true,
        "order": [[0, 'desc']],
        "initComplete": function() {
            loadStockStats();
            loadWarehouseOptions();
        }
    });

    // 加载库存统计数据
    function loadStockStats() {
        $.ajax({
            url: '/stock/stats',
            type: 'GET',
            success: function(res) {
                if (res.code === 200 && res.data) {
                    $('#totalStockCount').text(res.data.totalCount);
                    $('#totalStockValue').text('¥' + res.data.totalValue.toFixed(2));
                    $('#lowStockCount').text(res.data.lowStockCount);
                    $('#outOfStockCount').text(res.data.outOfStockCount);
                }
            }
        });
    }

    // 加载仓库选项
    function loadWarehouseOptions() {
        $.ajax({
            url: '/warehouse/list',
            type: 'GET',
            success: function(res) {
                if (res.code === 200 && res.data) {
                    let options = '<option value="">全部</option>';
                    res.data.forEach(function(warehouse) {
                        options += `<option value="${warehouse.warehouseId}">${warehouse.warehouseName}</option>`;
                    });
                    $('#searchWarehouse').html(options);
                    $('#warehouseId').html('<option value="">请选择仓库</option>' + options);
                }
            }
        });
    }

    // 绑定产品选择事件 - 获取产品信息
    $('#productId').change(function() {
        const productId = $(this).val();
        if (productId) {
            $.ajax({
                url: '/product/' + productId,
                type: 'GET',
                success: function(res) {
                    if (res.code === 200 && res.data) {
                        $('#unit').val(res.data.unit);
                        $('#price').val(res.data.price);
                        updateTotalValue();
                    }
                }
            });
        } else {
            $('#unit').val('');
            $('#price').val('');
            $('#totalValue').val('');
        }
    });

    // 输入库存数量时自动计算库存价值
    $('#quantity').on('input', function() {
        updateTotalValue();
    });

    // 出库数量输入校验
    $('#outQuantity').on('input', function() {
        const currentQuantity = parseInt($('#currentQuantity').val()) || 0;
        const outQuantity = parseInt($(this).val()) || 0;
        
        if (outQuantity > currentQuantity) {
            $('#outQuantityHelp').text('出库数量不能大于当前库存');
            $('#confirmOutStock').prop('disabled', true);
        } else if (outQuantity <= 0) {
            $('#outQuantityHelp').text('出库数量必须大于0');
            $('#confirmOutStock').prop('disabled', true);
        } else {
            $('#outQuantityHelp').text('');
            $('#confirmOutStock').prop('disabled', false);
        }
    });

    // 确认出库按钮
    $('#confirmOutStock').click(function() {
        if (!$('#outStockForm')[0].checkValidity()) {
            $('#outStockForm')[0].reportValidity();
            return;
        }
        
        const stockId = $('#outStockId').val();
        const outQuantity = $('#outQuantity').val();
        const outReason = $('#outReason').val();
        const outRemark = $('#outRemark').val();
        
        $.ajax({
            url: '/stock/out',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                stockId: stockId,
                quantity: outQuantity,
                reason: outReason,
                remark: outRemark
            }),
            success: function(res) {
                $('#outStockModal').modal('hide');
                if (res.code === 200) {
                    stockTable.ajax.reload();
                    loadStockStats();
                    alert('出库操作成功！');
                } else {
                    alert('出库操作失败: ' + (res.msg || '未知错误'));
                }
            },
            error: function(xhr) {
                alert('出库操作错误: ' + xhr.statusText);
            }
        });
    });
    
    // 模态框关闭时重置状态
    $('#stockModal').on('hidden.bs.modal', function () {
        $('#stockForm')[0].reset();
        $('#stockForm input, #stockForm select, #stockForm textarea').prop('disabled', false);
        $('.modal-footer .btn-primary').show();
        $('.modal-footer .btn-secondary').text('取消');
    });
});

// 更新库存价值
function updateTotalValue() {
    const quantity = parseFloat($('#quantity').val()) || 0;
    const price = parseFloat($('#price').val()) || 0;
    const totalValue = (quantity * price).toFixed(2);
    $('#totalValue').val(totalValue);
}

// 加载产品选项
function loadProductOptions() {
    $.ajax({
        url: '/product/list',
        type: 'GET',
        success: function(res) {
            if (res.code === 200 && res.data) {
                let options = '<option value="">请选择产品</option>';
                res.data.forEach(function(product) {
                    options += `<option value="${product.productId}">${product.productName} (${product.productCode})</option>`;
                });
                $('#productId').html(options);
            }
        }
    });
}

// 添加库存
function addStock() {
    editingId = null;
    $('#stockModalLabel').text('入库登记');
    $('#stockForm')[0].reset();
    $('#stockId').val('');
    $('#deleteBtn').hide();
    
    // 加载产品选项
    loadProductOptions();
    
    $('#stockModal').modal('show');
}

// 查看库存详情
function viewStock(id) {
    // 获取库存数据
    $.ajax({
        url: '/stock/' + id,
        type: 'GET',
        success: function(res) {
            if (res.code === 200 && res.data) {
                const stock = res.data;
                
                // 加载产品选项
                loadProductOptions();
                
                // 填充表单
                $('#stockId').val(stock.stockId);
                $('#productId').val(stock.productId);
                $('#warehouseId').val(stock.warehouseId);
                $('#quantity').val(stock.quantity);
                $('#unit').val(stock.unit);
                $('#price').val(stock.price);
                $('#totalValue').val((stock.quantity * stock.price).toFixed(2));
                $('#warningQuantity').val(stock.warningQuantity);
                $('#locationCode').val(stock.locationCode);
                $('#remark').val(stock.remark);
                
                // 设置字段为只读
                $('#stockForm input, #stockForm select, #stockForm textarea').prop('disabled', true);
                
                // 设置模态框标题和显示
                $('#stockModalLabel').text('查看库存详情');
                $('#deleteBtn').hide();
                
                // 隐藏保存按钮，修改关闭按钮文本
                $('.modal-footer .btn-primary').hide();
                $('.modal-footer .btn-secondary').text('关闭');
                
                $('#stockModal').modal('show');
            } else {
                alert('获取库存信息失败: ' + (res.msg || '未知错误'));
            }
        },
        error: function(xhr) {
            alert('获取库存信息错误: ' + xhr.statusText);
        }
    });
}

// 编辑库存
function editStock(id) {
    editingId = id;
    
    // 重置表单状态
    $('#stockForm')[0].reset();
    $('#stockForm input, #stockForm select, #stockForm textarea').prop('disabled', false);
    $('.modal-footer .btn-primary').show().text('保存');
    $('.modal-footer .btn-secondary').text('取消');
    
    // 加载产品选项
    loadProductOptions();
    
    // 获取库存数据
    $.ajax({
        url: '/stock/' + id,
        type: 'GET',
        success: function(res) {
            if (res.code === 200 && res.data) {
                const stock = res.data;
                
                // 填充表单
                $('#stockId').val(stock.stockId);
                $('#productId').val(stock.productId);
                $('#warehouseId').val(stock.warehouseId);
                $('#quantity').val(stock.quantity);
                $('#unit').val(stock.unit);
                $('#price').val(stock.price);
                $('#totalValue').val((stock.quantity * stock.price).toFixed(2));
                $('#warningQuantity').val(stock.warningQuantity);
                $('#locationCode').val(stock.locationCode);
                $('#remark').val(stock.remark);
                
                // 禁用产品选择，因为不应该修改已有库存的产品
                $('#productId').prop('disabled', true);
                
                // 设置模态框标题和显示
                $('#stockModalLabel').text('编辑库存');
                $('#deleteBtn').show();
                $('#stockModal').modal('show');
            } else {
                alert('获取库存信息失败: ' + (res.msg || '未知错误'));
            }
        },
        error: function(xhr) {
            alert('获取库存信息错误: ' + xhr.statusText);
        }
    });
}

// 保存库存信息
function saveStock() {
    // 表单验证
    if (!$('#stockForm')[0].checkValidity()) {
        $('#stockForm')[0].reportValidity();
        return;
    }
    
    // 收集表单数据
    const formData = {
        stockId: $('#stockId').val(),
        productId: $('#productId').val(),
        warehouseId: $('#warehouseId').val(),
        quantity: $('#quantity').val(),
        unit: $('#unit').val(),
        price: $('#price').val(),
        warningQuantity: $('#warningQuantity').val(),
        locationCode: $('#locationCode').val(),
        remark: $('#remark').val()
    };
    
    // 确定是入库还是更新
    const isNew = !formData.stockId;
    const url = '/stock';
    const method = isNew ? 'POST' : 'PUT';
    
    // 发送请求
    $.ajax({
        url: url,
        type: method,
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function(res) {
            if (res.code === 200) {
                $('#stockModal').modal('hide');
                stockTable.ajax.reload();
                loadStockStats();
                alert(isNew ? '入库登记成功！' : '更新库存成功！');
            } else {
                alert(isNew ? '入库登记失败: ' : '更新库存失败: ' + (res.msg || '未知错误'));
            }
        },
        error: function(xhr) {
            alert(isNew ? '入库登记错误: ' : '更新库存错误: ' + xhr.statusText);
        }
    });
}

// 显示出库对话框
function showOutStockModal(id) {
    // 获取库存数据
    $.ajax({
        url: '/stock/' + id,
        type: 'GET',
        success: function(res) {
            if (res.code === 200 && res.data) {
                const stock = res.data;
                
                // 填充表单
                $('#outStockId').val(stock.stockId);
                $('#outProductName').val(stock.productName);
                $('#outWarehouseName').val(stock.warehouseName);
                $('#currentQuantity').val(stock.quantity);
                $('#outUnit').val(stock.unit);
                $('#outQuantity').val('');
                $('#outReason').val('');
                $('#outRemark').val('');
                
                // 重置出库数量帮助信息和按钮状态
                $('#outQuantityHelp').text('');
                $('#confirmOutStock').prop('disabled', true);
                
                $('#outStockModal').modal('show');
            } else {
                alert('获取库存信息失败: ' + (res.msg || '未知错误'));
            }
        },
        error: function(xhr) {
            alert('获取库存信息错误: ' + xhr.statusText);
        }
    });
}

// 显示删除确认对话框
function showDeleteModal(id) {
    editingId = id;
    $('#deleteModal').modal('show');
}

// 从编辑模态框中删除
function confirmDelete() {
    if (editingId) {
        $('#stockModal').modal('hide');
        setTimeout(() => {
            $('#deleteModal').modal('show');
        }, 500);
    }
}

// 删除库存
function deleteStock() {
    if (editingId) {
        $.ajax({
            url: '/stock/' + editingId,
            type: 'DELETE',
            success: function(res) {
                $('#deleteModal').modal('hide');
                if (res.code === 200) {
                    stockTable.ajax.reload();
                    loadStockStats();
                    alert('删除库存成功！');
                } else {
                    alert('删除库存失败: ' + (res.msg || '未知错误'));
                }
            },
            error: function(xhr) {
                $('#deleteModal').modal('hide');
                alert('删除库存错误: ' + xhr.statusText);
            }
        });
    }
}

// 搜索库存
function searchStock() {
    const params = {
        productName: $('#searchProductName').val(),
        productCode: $('#searchProductCode').val(),
        warehouseId: $('#searchWarehouse').val(),
        status: $('#searchStatus').val()
    };
    
    // 重新加载表格数据
    stockTable.ajax.url('/stock/list?' + $.param(params)).load();
}

// 重置搜索
function resetSearch() {
    $('#searchForm')[0].reset();
    stockTable.ajax.url('/stock/list').load();
}

// 导出库存数据
function exportStockData() {
    const params = {
        productName: $('#searchProductName').val(),
        productCode: $('#searchProductCode').val(),
        warehouseId: $('#searchWarehouse').val(),
        status: $('#searchStatus').val()
    };
    
    alert('导出功能待实现');
    // window.location.href = '/stock/export?' + $.param(params);
} 